package com.simtop.service.impl;

import com.simtop.common.ServerResponse;
import com.simtop.dao.CountDao;
import com.simtop.dao.UserDao;
import com.simtop.pojo.Operate;
import com.simtop.pojo.User;
import com.simtop.service.JwtLoginService;
import com.simtop.util.JwtUtil;
import com.simtop.util.MD5;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * JWT业务验证类
 */
@Service
public class JwtLoginServiceImpl implements JwtLoginService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private CountDao countDao;

    @Override
    public ServerResponse<String> login(User user) {
        //验证成功返回token
        user.setPassword(MD5.md52(user.getPassword()));
        User u = userDao.checkLoginNameOrEmail(user.getLoginName(),user.getEmail());
        if(u == null){
            return ServerResponse.createByErrorMsg("登录名不存在");
        }
        //如果登陆成功
        if(u.getPassword().equals(user.getPassword()) && u.getRoleId().equals(user.getRoleId())){
            Operate operate = new Operate("用户登录",u.getUsername(),"登录成功",null,null,u.getRoleId());
            userDao.insertOperate(operate);
            //使用JWT加密生成token todo
            //置空密码
            u.setPassword(StringUtils.EMPTY);
            // todo important token有效期24个小时
            String token = JwtUtil.sign(u,60L*1000*60*24L);
            /**
             * todo 统计网站访问次数：登陆成功后统计次数变量count加1
             */
            int num = countDao.selectCount();
            int count = ++num;
            countDao.updateOne(count);
            return ServerResponse.createBySuccess(String.valueOf(u.getExercises()),token);
        }else if(!(u.getRoleId().equals(user.getRoleId()))){
            Operate operate = new Operate("用户登录",u.getUsername(),"登录失败，角色错误",null,null,u.getRoleId());
            userDao.insertOperate(operate);
            return ServerResponse.createByErrorMsg("角色错误");
        }
        Operate operate = new Operate("用户登录",u.getUsername(),"登录失败，登陆密码错误",null,null,u.getRoleId());
        userDao.insertOperate(operate);
        return ServerResponse.createByErrorMsg("登陆密码错误");
    }
}
